<?php
namespace app\adminjcb\controller;

use app\adminjcb\model\Member as MemberModel;
use app\common\controller\AdminBaseController;
use think\Config;
use think\Db;

/**
 * 用户管理
 * Class Member
 */
class MemberController extends AdminBaseController {
    protected $member_model;

    protected function _initialize() {
        parent::_initialize();
        $this->member_model = new MemberModel();
    }

    /**
     * 用户管理
     * @param string $keyword
     * @param int    $page
     * @return mixed
     */
    public function index($keyword = '', $ziduan = 'id', $param='add_time', $sort='desc') {
        $map = [];
		$order = $param. ' '.$sort;
		$this->assign('param', $param);
		$this->assign('sort', $sort);
        if ($keyword) {
            $map[$ziduan] = $keyword;
        }
		$this->assign('ziduan', $ziduan);
        $member_list = $this->member_model->where($map)->order($order)->paginate(15, false, get_query());
		$moneys = db('member')->sum('money');
		$this->assign('moneys', $moneys);
		$frozen_moneys = db('member')->sum('frozen_money');
		$this->assign('frozen_moneys', $frozen_moneys);
		$coins = db('member')->sum('coin');
		$this->assign('coins', $coins);
		$trade_coins = db('member')->sum('trade_coin');
		$this->assign('trade_coins', $trade_coins);
		$tui_coins = db('member')->sum('tui_coin');
		$this->assign('tui_coins', $tui_coins);
        return $this->fetch('index', ['member_list' => $member_list, 'keyword' => $keyword]);
    }
	public function export(){
    	$list = db('member')->order('add_time desc')->select();
		$str ="ID,会员名,手机号,余额,消费金额,注册时间"."\n";
        $str = iconv('utf-8','gbk',$str);
        foreach($list as $k=>$row){
        	$id = iconv('utf-8','gbk',$row['id']);
			$nickname = iconv('utf-8','gbk',$row['real_name'].'	');  
			$mobile = iconv('utf-8','gbk',$row['mobile'].'	');
			$money = iconv('utf-8','gbk',$row['money']);
			$add_time = iconv('utf-8','gbk',$row['add_time']);
			
			$str .= $id.",".$nickname.",".$mobile.",".$money.",".$add_time."\n"; //用引文逗号分开 
        } 

	  	$filename ='会员列表.csv';   //设置文件名  
    	
        header("Content-type:text/csv"); 
        header("Content-Disposition:attachment;filename=".$filename); 
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0'); 
        header('Expires:0'); 
        header('Pragma:public'); 
        echo $str; 
        exit;
	}
	/**
     * 用户管理
     * @param string $keyword
     * @param int    $page
     * @return mixed
     */
    public function jihuo($keyword = '', $ziduan = 'id') {
        $map = [];
		$map['status'] = 0;
        if ($keyword) {
            $map[$ziduan] = $keyword;
        }
        $member_list = $this->member_model->where($map)->order('add_time DESC')->paginate(15, false, ['query' => ['keyword' => $keyword]]);
        return $this->fetch('jihuo', ['member_list' => $member_list, 'keyword' => $keyword]);
    }

    /**
     * 添加用户
     * @return mixed
     */
    public function add() {
        return $this->fetch();
    }

    /**
     * 保存用户
     */
    public function save() {
        if ($this->request->isPost()) {
            $data            = $this->request->post();
            $validate_result = $this->validate($data, 'Member');
            if ($validate_result !== true) {
                $this->error($validate_result);
            } else {
            	$password = $data['password'];
                $data['password'] = md5_salt($password);
                $data['pay_password'] = md5_salt($password);
                if ($this->member_model->allowField(true)->save($data)) {
                    $this->success('添加成功');
                } else {
                    $this->error('添加失败');
                }
            }
        }
    }

    /**
     * 编辑用户
     * @param $id
     * @return mixed
     */
    public function edit($id) {
        $member = $this->member_model->find($id);
        return $this->fetch('edit', ['member' => $member]);
    }

    /**
     * 更新用户
     * @param $id
     */
    public function update($id) {
        if ($this->request->isPost()) {
            $data            = $this->request->post();
            $validate_result = $this->validate($data, 'Member');

            if ($validate_result !== true) {
                $this->error($validate_result);
            } else {
                if (!empty($data['password'])) {
                    $data['password'] = md5_salt($data['password']);
                }else{
                	$data['password'] = $data['old_pwd'];
                }
				if (!empty($data['pay_password'])) {
                    $data['pay_password'] = md5_salt($data['pay_password']);
                }else{
                	$data['pay_password'] = $data['old_pay_pwd'];
                }
                if ($this->member_model->allowField(true)->save($data,['id'=>$id]) !== false) {
                    $this->success('更新成功');
                } else {
                    $this->error('更新失败');
                }
            }
        }
    }
	
	/**
     * 更新余额
     * @param $id
     */
    public function score() {
        if ($this->request->isPost()) {
            $data  = $this->request->post();
			$member = db("member")->where('mobile', $data['mobile'])->find();
            if (!$member) {
            	$this->error('会员账号不存在');
            }
			$admin = db('user')->where('id', session('admin_id'))->find();
			if(md5_salt($data['password'])!=$admin['login_pwd']){
				$this->error('管理员密码错误');
			}
        	$result = db("member")->where('mobile', $data['mobile'])->setInc('money',$data['score']);
            if($result){
            	add_money_log('余额充值', '系统余额充值到账', $data['score'], $member['id']);
            	$this->success('充值成功');
            }else{
            	 $this->error('充值失败');
            }
        }else{
        	$this->assign('mobile', input('mobile'));
        	return $this->fetch();
        }
    }
	
	/**
     * 更新币
     * @param $id
     */
    public function coin() {
        if ($this->request->isPost()) {
            $data  = $this->request->post();
			$member = db("member")->where('mobile', $data['mobile'])->find();
            if (!$member) {
            	$this->error('会员账号不存在');
            }
			$admin = db('user')->where('id', session('admin_id'))->find();
			if(md5_salt($data['password'])!=$admin['login_pwd']){
				$this->error('管理员密码错误');
			}
        	$result = db("member")->where('mobile', $data['mobile'])->setInc('coin',$data['score']);
            if($result){
            	add_coin_log('币充值', '系统币充值到账', $data['score'], $member['id']);
            	$this->success('充值成功');
            }else{
            	 $this->error('充值失败');
            }
        }else{
        	$this->assign('mobile', input('mobile'));
        	return $this->fetch();
        }
    }
	
    /**
     * 删除用户
     * @param $id
     */
    public function delete($id) {
        if ($this->member_model->destroy($id)) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }
	
	public function login($id) {
		// 直接登录
		$result = db("member") -> find($id);
		if($result){
			$data['login_time'] = now_time();
			$data['login_ip'] = $this->request->ip();
			$data['session_id'] = session_id();  //更改登录状态
			$this->member_model->save($data,['id'=>$id]);
			session('USER',$result);
			$this->success('登录成功！','index/member/index');
		}else{
			$this->error('登录失败');
		}
	}

}
